var user_name = '';
// 假设服务端ip为127.0.0.1
ws = new WebSocket("ws://39.106.5.38:8246");

// 连接时的回调
ws.onopen = function() {
    var username_arr = ['张三', 'OK', '人防', '乐呵', '问问', '哈哈', '信息', '赵六', '王五', '李四'];
    var uid = randomNum(1,999999);
    var username = username_arr[randomNum(1,9)];
    var msg_obj = {"action_type":"login", 'uid': uid,"username":username};
    var msg = JSON.stringify(msg_obj);
    ws.send(msg);
};

// 收到服务端的回调
ws.onmessage = function(e) {
    var msg_obj = JSON.parse(e.data);
    user_name = msg_obj.username;
    if(msg_obj.action_type == 'new_user'){
        var html = '<div class="new-user"><a href="#">'+msg_obj.username+'</a>'+msg_obj.text+'</div>';
        show_users(msg_obj.users);
        $('.msg-list-box').append(html);
        message_scrollTop();
    }else if(msg_obj.action_type == 'new_msg'){
        if(msg_obj.is_my == 1){
            var html = '<div class="msg"><span class="username my">'+msg_obj.username+'</span><span class="msg-data">'+msg_obj.content+'</span></div>';
        }else{
            var html = '<div class="msg"><span class="username">'+msg_obj.username+'</span><span class="msg-data">'+msg_obj.content+'</span></div>';
        }
        $('.msg-list-box').append(html);
        message_scrollTop();
    }
    if(msg_obj.action_type == 'user_count'){
        $('#user_count').html(msg_obj.user_count);
    }else if(msg_obj.action_type == 'user_close'){
        show_users(msg_obj.users);
        $('#user_count').html(msg_obj.user_count);
    }
};

//用户列表显示
function show_users (users){
    $('#users-box').html('');
    var html = '';
    $.each(users, function(index, value){
        html += '<a href="#" id="user_'+value.uid+'">'+value.username+'</a>';
    });
    $('#users-box').append(html);
}
// 信息发送方法
function send(){
    var content = $('#msg-text').val();
    $('#msg-text').val('');
    var msg_obj = {'action_type':'send_msg', 'content': content, 'username': user_name};
    var msg = JSON.stringify(msg_obj);
    ws.send(msg);
}

// 测试自定义方法
function randomNum(minNum, maxNum){
    switch(arguments.length){
        case 1:
            return parseInt(Math.random()*minNum+1,10);
        break;
        case 2:
            return parseInt(Math.random()*(maxNum-minNum+1),10);
        break;
        default:
            return 0;
        break;
    }
}
// 接受信息滚动条置底
function message_scrollTop(){
    $('.msg-list-box').scrollTop($('.msg-list-box')[0].scrollHeight)
}
// 监听回车键
$(document).keyup(function(event){
    if(event.keyCode == 13){
        send();
    }
});

start();
function start(){
    var pswd = prompt('请输入临时密码进入');
    if(pswd != 'Admin123456789'){
        alert('密码错误，请重新输入');
        location.reload()
    }else{
        alert('密码正确');
    }
}